package com.mk.service;

import com.mk.constant.RedisCacheConstant;
import com.mk.entity.Chat;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * 聊天的Redis服务
 */
@Service
public class ChatRedisService {
    private final RedisTemplate<String, Object> redisTemplate;

    public ChatRedisService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 存储消息到 Redis（LPUSH 方式）
    public void saveMessage(Chat message) {
        redisTemplate.opsForList().leftPush(RedisCacheConstant.CHAT_KEY, message);
    }

    // 从 Redis 读取并清空消息（LPOP 方式）
    public List<Object> fetchAndClearMessages() {
        return redisTemplate.opsForList().range(RedisCacheConstant.CHAT_KEY, 0, -1);
    }

    public void clearMessages() {
        redisTemplate.delete(RedisCacheConstant.CHAT_KEY);
    }
}
